package soar.template.springboot.mq.alimq.consumer.configuration.alimq;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.ons.api.bean.ConsumerBean;
import com.aliyun.openservices.ons.api.bean.Subscription;

import soar.template.springboot.mq.alimq.consumer.app.MessageConsumer;
import soar.template.springboot.mq.alimq.consumer.appconfig.AppConfig;
import soar.template.springboot.mq.alimq.consumer.appconfig.alimq.ReceiveConfig;

@Configuration
class MyAliMQConfiguration
{
    @Resource(name = "appconfig")
    private AppConfig appconfig;

    /*--- 监听接收 ---*/
    @Resource
    private MessageConsumer messageConsumer;

    @Bean(initMethod = "start", destroyMethod = "shutdown")
    public ConsumerBean receiveMainConsumer() throws Exception
    {
        return create_consumer(appconfig.alimq.receiveMain, messageConsumer);
    }

    private ConsumerBean create_consumer(ReceiveConfig config,
            MessageListener message_listener)
    {
        ConsumerBean consumer = new ConsumerBean();

        Properties props = new Properties();
        props.setProperty(PropertyKeyConst.ConsumerId, config.consumerId);
        props.setProperty(PropertyKeyConst.AccessKey, config.accessKey);
        props.setProperty(PropertyKeyConst.SecretKey, config.secretKey);
        props.setProperty(PropertyKeyConst.ONSAddr, config.ONSAddr);
        props.setProperty(PropertyKeyConst.ConsumeThreadNums,
                String.valueOf(10));
        consumer.setProperties(props);

        Map<Subscription, MessageListener> subscription_table = new HashMap<>();
        Subscription subscription = new Subscription();
        subscription.setTopic(config.topic);
        subscription.setExpression("*");
        subscription_table.put(subscription, message_listener);
        consumer.setSubscriptionTable(subscription_table);

        return consumer;
    }
}
